<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.4.2">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/font-awesome.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"eryangz.gitee.io","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":true,"show_result":true,"style":"mac"},"back2top":{"enable":true,"sidebar":false,"scrollpercent":true},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="一、单例模式定义及实现原理单例模式最初的定义出现于《设计模式》（艾迪生维斯理, 1994）：“保证一个类仅有一个实例，并提供一个访问它的全局访问点。” 实现原理：实现单例模式需要保证一个类只要实例化一个对象，下一次再进行实例化的时候就直接返回单例对象，不再做实例化的操作。这里面的关键一点就是如何判断这个类是否实例化过一个对象。 python中常用的几类实现方式：  通过模块导入 使用装饰器 使用类">
<meta property="og:type" content="article">
<meta property="og:title" content="初识单例模式和工厂模式">
<meta property="og:url" content="https://eryangz.gitee.io/20190120/%E5%88%9D%E8%AF%86%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%E5%92%8C%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F/index.html">
<meta property="og:site_name" content="二扬">
<meta property="og:description" content="一、单例模式定义及实现原理单例模式最初的定义出现于《设计模式》（艾迪生维斯理, 1994）：“保证一个类仅有一个实例，并提供一个访问它的全局访问点。” 实现原理：实现单例模式需要保证一个类只要实例化一个对象，下一次再进行实例化的时候就直接返回单例对象，不再做实例化的操作。这里面的关键一点就是如何判断这个类是否实例化过一个对象。 python中常用的几类实现方式：  通过模块导入 使用装饰器 使用类">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2019-01-20T12:20:56.000Z">
<meta property="article:modified_time" content="2023-05-20T09:54:57.071Z">
<meta property="article:author" content="二扬">
<meta property="article:tag" content="python">
<meta property="article:tag" content="设计模式">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="https://eryangz.gitee.io/20190120/%E5%88%9D%E8%AF%86%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%E5%92%8C%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'zh-CN'
  };
</script>

  <title>初识单例模式和工厂模式 | 二扬</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">二扬</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">blog</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-fw fa-home"></i>首页</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-fw fa-user"></i>关于</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-fw fa-tags"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-fw fa-th"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-fw fa-archive"></i>归档</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://eryangz.gitee.io/20190120/%E5%88%9D%E8%AF%86%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%E5%92%8C%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="二扬">
      <meta itemprop="description" content="念念不忘, 必有回响">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="二扬">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          初识单例模式和工厂模式
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2019-01-20 20:20:56" itemprop="dateCreated datePublished" datetime="2019-01-20T20:20:56+08:00">2019-01-20</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="fa fa-calendar-check-o"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2023-05-20 17:54:57" itemprop="dateModified" datetime="2023-05-20T17:54:57+08:00">2023-05-20</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/python/" itemprop="url" rel="index"><span itemprop="name">python</span></a>
                </span>
            </span>

          <br>
            <span class="post-meta-item" title="本文字数">
              <span class="post-meta-item-icon">
                <i class="fa fa-file-word-o"></i>
              </span>
                <span class="post-meta-item-text">本文字数：</span>
              <span>16k</span>
            </span>
            <span class="post-meta-item" title="阅读时长">
              <span class="post-meta-item-icon">
                <i class="fa fa-clock-o"></i>
              </span>
                <span class="post-meta-item-text">阅读时长 &asymp;</span>
              <span>14 分钟</span>
            </span>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <h1 id="一、单例模式"><a href="#一、单例模式" class="headerlink" title="一、单例模式"></a>一、单例模式</h1><h3 id="定义及实现原理"><a href="#定义及实现原理" class="headerlink" title="定义及实现原理"></a>定义及实现原理</h3><p>单例模式最初的定义出现于《设计模式》（艾迪生维斯理, 1994）：“保证一个类仅有一个实例，并提供一个访问它的全局访问点。”</p>
<p>实现原理：实现单例模式需要保证一个类只要实例化一个对象，下一次再进行实例化的时候就直接返回单例对象，不再做实例化的操作。这里面的关键一点就是<strong>如何判断这个类是否实例化过一个对象。</strong></p>
<p>python中常用的几类实现方式：</p>
<ul>
<li>通过模块导入</li>
<li>使用装饰器</li>
<li>使用类方法、魔法方法实现</li>
<li>元类实现</li>
</ul>
<h5 id="通过模块实现"><a href="#通过模块实现" class="headerlink" title="通过模块实现"></a>通过模块实现</h5><p>在<code>singleton_case.py</code>文件中定义此段代码</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Singleton</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">do_something</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">singleton = Singleton()</span><br><span class="line"><span class="built_in">print</span>(<span class="string">f&quot;<span class="subst">&#123;__name__&#125;</span>: <span class="subst">&#123;singleton&#125;</span>&quot;</span>)</span><br></pre></td></tr></table></figure>

<p>在<code>singleton.py</code>中使用</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">from</span> singleton_case <span class="keyword">import</span> singleton, Singleton</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">import_case</span>():</span></span><br><span class="line">    <span class="string">&quot;&quot;&quot;基于模块导入实现&quot;&quot;&quot;</span></span><br><span class="line">    not_singleton = Singleton()</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">f&quot;<span class="subst">&#123;__name__&#125;</span>-singleton<span class="subst">&#123;singleton&#125;</span>*****not_singleton<span class="subst">&#123;not_singleton&#125;</span>&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    import_case()	</span><br><span class="line">    import_case()</span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">Output</span></span><br><span class="line"><span class="string">    singleton_case: &lt;singleton_case.Singleton object at 0x000001D2716E4BE0&gt;</span></span><br><span class="line"><span class="string">    __main__-singleton&lt;singleton_case.Singleton object at 0x000001A7C6E44BE0&gt;**not_singleton&lt;singleton_case.Singleton object at 0x000001A7C6BDE278&gt;</span></span><br><span class="line"><span class="string">    __main__-singleton&lt;singleton_case.Singleton object at 0x000001A7C6E44BE0&gt;**not_singleton&lt;singleton_case.Singleton object at 0x000001A7C6BDE278&gt;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">实现原理：</span></span><br><span class="line"><span class="string">    python模块导入时的原理：当一个模块（py文件）被导入时，首先会执行这个模块的代码，然后将这个模块的名称空间加载到内存。</span></span><br><span class="line"><span class="string">    当这个模块第二次再被导入时，不会再执行该文件，而是直接在内存中找。于是，如果第一次导入模块，执行文件源代码时实例化了一个类，</span></span><br><span class="line"><span class="string">    那再次导入的时候，就不会再实例化。</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<h5 id="通过装饰器实现"><a href="#通过装饰器实现" class="headerlink" title="通过装饰器实现"></a>通过装饰器实现</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">singleton</span>(<span class="params">cls</span>):</span></span><br><span class="line">    _instance = &#123;&#125;</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">inner</span>(<span class="params">*args, **kwargs</span>):</span></span><br><span class="line">        <span class="keyword">if</span> cls <span class="keyword">not</span> <span class="keyword">in</span> _instance:</span><br><span class="line">            _instance[cls] = cls(*args, **kwargs)</span><br><span class="line">        <span class="keyword">return</span> _instance[cls]</span><br><span class="line">    <span class="keyword">return</span> inner</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@singleton</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">People</span>:</span>   <span class="comment"># singleton(People)</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, name</span>):</span></span><br><span class="line">        self.name = name</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SingleTon</span>:</span></span><br><span class="line">    _instance_dict = &#123;&#125;     <span class="comment"># &#123;Car: 实例化对象, xx类: 实例化对象&#125;</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, cls_name</span>):</span></span><br><span class="line">        self.cls_name = cls_name</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__call__</span>(<span class="params">self, *args, **kwargs</span>):</span></span><br><span class="line">        <span class="keyword">if</span> self.cls_name <span class="keyword">not</span> <span class="keyword">in</span> SingleTon._instance_dict:</span><br><span class="line">            SingleTon._instance_dict[self.cls_name] = self.cls_name(*args, **kwargs)</span><br><span class="line">        <span class="keyword">return</span> SingleTon._instance_dict.get(self.cls_name)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="meta">@SingleTon  </span><span class="comment"># Car(&quot;linco&quot;) = SingleTon(Car(&quot;linco&quot;)) -&gt; __call__   Car(&quot;linco&quot;)为SingleTon实例化对象</span></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Car</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, name</span>):</span></span><br><span class="line">        self.name = name</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    p1 = People(<span class="string">&quot;小明&quot;</span>)</span><br><span class="line">    p2 = People(<span class="string">&quot;小王&quot;</span>)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">f&quot;小明: <span class="subst">&#123;p1&#125;</span>-----小王：<span class="subst">&#123;p2&#125;</span>&quot;</span>)</span><br><span class="line"></span><br><span class="line">    c1 = Car(<span class="string">&quot;linco&quot;</span>)</span><br><span class="line">    c2 = Car(<span class="string">&quot;c260l&quot;</span>)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">f&quot;Car: <span class="subst">&#123;<span class="built_in">type</span>(Car)&#125;</span>---linco: <span class="subst">&#123;c1&#125;</span>-----c260l：<span class="subst">&#123;c2&#125;</span>&quot;</span>)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">Output</span></span><br><span class="line"><span class="string">	小明: &lt;__main__.People object at 0x000002921A79A630&gt;-----小王：&lt;__main__.People object at 0x000002921A79A630&gt;</span></span><br><span class="line"><span class="string">	Car: &lt;class &#x27;__main__.SingleTon&#x27;&gt;---linco: &lt;__main__.Car object at 0x000002921A79A668&gt;-----c260l：&lt;__main__.Car object at 0x000002921A79A668&gt;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">在函数装饰器的思路上，将装饰器封装成类。</span></span><br><span class="line"><span class="string">    程序执行到语法糖时，会实例化一个Car对象，这个对象是SingleTon的对象。</span></span><br><span class="line"><span class="string">    后面使用的Car本质上使用的是SingleTon的对象。</span></span><br><span class="line"><span class="string">    所以使用Car(&quot;linco&quot;)来实例化对象，其实是在调用SingleTon的对象，会触发其__call__的执行</span></span><br><span class="line"><span class="string">    所以就在__call__中，判断Car类有没有实例对象了。</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<h5 id="使用类方法、魔法方法"><a href="#使用类方法、魔法方法" class="headerlink" title="使用类方法、魔法方法"></a>使用类方法、魔法方法</h5><p>使用类方法实现单例模式</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Singleton</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, name</span>):</span></span><br><span class="line">        self.name = name</span><br><span class="line"></span><br><span class="line"><span class="meta">    @classmethod</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">get_instance</span>(<span class="params">cls, *args, **kwargs</span>):</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> <span class="built_in">hasattr</span>(Singleton, <span class="string">&quot;_instance&quot;</span>):</span><br><span class="line">            Singleton._instance = Singleton(*args, **kwargs)</span><br><span class="line">        <span class="keyword">return</span> Singleton._instance</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    p1 = Singleton.get_instance(<span class="string">&quot;小明&quot;</span>)</span><br><span class="line">    p2 = Singleton.get_instance(<span class="string">&quot;小王&quot;</span>)</span><br><span class="line">    p3 = Singleton(<span class="string">&quot;小明2&quot;</span>)</span><br><span class="line">    p4 = Singleton(<span class="string">&quot;小王2&quot;</span>)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">f&quot;小明: <span class="subst">&#123;p1&#125;</span>-----小王：<span class="subst">&#123;p2&#125;</span>&quot;</span>)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">f&quot;小明: <span class="subst">&#123;p3&#125;</span>-----小王：<span class="subst">&#123;p4&#125;</span>&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">Output</span></span><br><span class="line"><span class="string">	小明: &lt;__main__.Singleton object at 0x000001D2A8FB4BE0&gt;-----小王：&lt;__main__.Singleton object at 0x000001D2A8FB4BE0&gt;</span></span><br><span class="line"><span class="string">	小明: &lt;__main__.Singleton object at 0x000001D2A8FB4CF8&gt;-----小王：&lt;__main__.Singleton object at 0x000001D2A8FB4CC0&gt;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">原理：类的方法</span></span><br><span class="line"><span class="string">    第一次实例化的对象保存成类的数据属性 _instance，</span></span><br><span class="line"><span class="string">    第二次再实例化时，在get_instance中判断已经有了实例对象，直接返回类的数据属性 _instance</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">这种方式实现的单例模式有一个明显的问题；如果不通过类的方法实例化对象，而是直接通过类名加括号实例化对象，那这样不再是单例模式</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<p>使用魔法方法<code>__new__</code>实现</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Singleton</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, name</span>):</span></span><br><span class="line">        self.name = name</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__new__</span>(<span class="params">cls, *args, **kwargs</span>):</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> <span class="built_in">hasattr</span>(cls, <span class="string">&quot;_instance&quot;</span>):</span><br><span class="line">            cls._instance = <span class="built_in">object</span>.__new__(cls)</span><br><span class="line">        <span class="keyword">return</span> cls._instance</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    p1 = Singleton(<span class="string">&quot;小明&quot;</span>)</span><br><span class="line">    p2 = Singleton(<span class="string">&quot;小王&quot;</span>)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">f&quot;小明: <span class="subst">&#123;p1&#125;</span>-----小王：<span class="subst">&#123;p2&#125;</span>&quot;</span>)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">Output</span></span><br><span class="line"><span class="string">	小明: &lt;__main__.Singleton object at 0x00000117D6844BA8&gt;-----小王：&lt;__main__.Singleton object at 0x00000117D6844BA8&gt;</span></span><br><span class="line"><span class="string"></span></span><br><span class="line"><span class="string">原理：将判断的实现方式，放在到类的__new__中,归根结底都是 判断类有没有实例，有则直接返回，无则实例化并保存到_instance中。</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<h5 id="元类实现"><a href="#元类实现" class="headerlink" title="元类实现"></a>元类实现</h5><figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br></pre></td><td class="code"><pre><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">SingletonType</span>(<span class="params"><span class="built_in">type</span></span>):</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">cls, name, bases, dic</span>):</span></span><br><span class="line">        <span class="built_in">super</span>().__init__(name, bases, dic)</span><br><span class="line">        cls._instance = <span class="literal">None</span>  <span class="comment"># 定义类时添加属性</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__call__</span>(<span class="params">cls, *args, **kwargs</span>):</span></span><br><span class="line">        <span class="keyword">if</span> cls._instance:  <span class="comment"># 判断类有没有实例化对象</span></span><br><span class="line">            <span class="keyword">return</span> cls._instance</span><br><span class="line">        <span class="keyword">else</span>:  <span class="comment"># 没有实例化对象时,生成实例化对象</span></span><br><span class="line">            obj = cls.__new__(cls, *args, **kwargs)</span><br><span class="line">            obj.__init__(*args, **kwargs)   <span class="comment"># 初始化类的实例化对象</span></span><br><span class="line">            cls._instance = obj  <span class="comment"># 保存对象，下一次再实例化可以直接返回而不用再造对象</span></span><br><span class="line">            <span class="keyword">return</span> obj</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">People</span>(<span class="params">metaclass=SingletonType</span>):</span>  <span class="comment"># People为SingletonType的对象  People = SingletonType()</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, name</span>):</span></span><br><span class="line">        self.name = name</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&#x27;__main__&#x27;</span>:</span><br><span class="line">    <span class="built_in">print</span>(People.__dict__)</span><br><span class="line">    p1 = People(<span class="string">&quot;小明&quot;</span>)   <span class="comment"># p1 = People()  -&gt; SingletonType __call__</span></span><br><span class="line">    p2 = People(<span class="string">&quot;小王&quot;</span>)</span><br><span class="line">    <span class="built_in">print</span>(<span class="string">f&quot;小明: <span class="subst">&#123;p1&#125;</span>-----小王：<span class="subst">&#123;p2&#125;</span>&quot;</span>)</span><br><span class="line">    <span class="built_in">print</span>(People.__dict__)</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">Output</span></span><br><span class="line"><span class="string">    &#123;&#x27;__module__&#x27;: &#x27;__main__&#x27;, &#x27;__init__&#x27;: &lt;function People.__init__ at 0x000002AEE60776A8&gt;, &#x27;__dict__&#x27;: &lt;attribute &#x27;__dict__&#x27; of &#x27;People&#x27; objects&gt;, &#x27;__weakref__&#x27;: &lt;attribute &#x27;__weakref__&#x27; of &#x27;People&#x27; objects&gt;, &#x27;__doc__&#x27;: None, &#x27;_instance&#x27;: None&#125;</span></span><br><span class="line"><span class="string">    小明: &lt;__main__.People object at 0x000002AEE6074EB8&gt;-----小王：&lt;__main__.People object at 0x000002AEE6074EB8&gt;</span></span><br><span class="line"><span class="string">    &#123;&#x27;__module__&#x27;: &#x27;__main__&#x27;, &#x27;__init__&#x27;: &lt;function People.__init__ at 0x000002AEE60776A8&gt;, &#x27;__dict__&#x27;: &lt;attribute &#x27;__dict__&#x27; of &#x27;People&#x27; objects&gt;, &#x27;__weakref__&#x27;: &lt;attribute &#x27;__weakref__&#x27; of &#x27;People&#x27; objects&gt;, &#x27;__doc__&#x27;: None, &#x27;_instance&#x27;: &lt;__main__.People object at 0x000002AEE6074EB8&gt;&#125;</span></span><br><span class="line"><span class="string">    </span></span><br><span class="line"><span class="string">原理：类定义时会调用元类下的__init__，类调用(实例化对象)时会触发元类下的__call__方法</span></span><br><span class="line"><span class="string">    类定义时，给类新增一个空的数据属性，</span></span><br><span class="line"><span class="string">    第一次实例化时，实例化之后就将这个对象赋值给类的数据属性；第二次再实例化时，直接返回类的这个数据属性</span></span><br><span class="line"><span class="string">    </span></span><br><span class="line"><span class="string">与类的方法实现、__new__实现相比：</span></span><br><span class="line"><span class="string">    类的这个_instance是放在元类中自动定义的，而不是在类中显示的定义的。</span></span><br><span class="line"><span class="string">    类调用时触发元类__call__方法判断是否有实例化对象，而不是在类的方法中判断</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<h5 id="多线程并发情况下单例模式的优化"><a href="#多线程并发情况下单例模式的优化" class="headerlink" title="多线程并发情况下单例模式的优化"></a>多线程并发情况下单例模式的优化</h5><p>问题：多线程并发情况下，多线程高并发时，如果同时有多个线程同一时刻（极端条件下）事例化对象，那么就会出现多个对象，这就不再是单例模式了，以<code>__new__</code>实现方式举例：</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">import</span> threading</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Singleton</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, name</span>):</span></span><br><span class="line">        self.name = name</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__new__</span>(<span class="params">cls, *args, **kwargs</span>):</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> <span class="built_in">hasattr</span>(cls, <span class="string">&quot;_instance&quot;</span>):</span><br><span class="line">            time.sleep(<span class="number">1</span>)   <span class="comment"># 耗时操作</span></span><br><span class="line">            cls._instance = <span class="built_in">object</span>.__new__(cls)</span><br><span class="line">        <span class="keyword">return</span> cls._instance</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">task</span>(<span class="params">name</span>):</span></span><br><span class="line">    obj = Singleton2(name)</span><br><span class="line">    <span class="built_in">print</span>(obj)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">20</span>):</span><br><span class="line">    t = threading.Thread(target=task, args=[i, ])</span><br><span class="line">    t.start()</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">Output</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E48F7B8&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E48F828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E3D4C88&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E3DAF28&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E46F4E0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E46F2E8&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E46F550&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E477198&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E479A58&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E477198&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E4797B8&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E477198&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E479668&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E477198&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E4796D8&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E477198&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E479F98&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E477198&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E479E48&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000022D0E477198&gt;</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<p>解决：判断是否存在实例及实例化对象操作的部分加一把锁，这样同时来的多个线程就需要排队</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">import</span> threading</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Singleton2</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line"></span><br><span class="line">    _instance_lock = threading.RLock()</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, name</span>):</span></span><br><span class="line">        self.name = name</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__new__</span>(<span class="params">cls, *args, **kwargs</span>):</span></span><br><span class="line">        <span class="keyword">with</span> cls._instance_lock:</span><br><span class="line">            <span class="keyword">if</span> <span class="keyword">not</span> <span class="built_in">hasattr</span>(cls, <span class="string">&quot;_instance&quot;</span>):</span><br><span class="line">                time.sleep(<span class="number">1</span>)   <span class="comment"># 耗时操作</span></span><br><span class="line">                cls._instance = <span class="built_in">object</span>.__new__(cls)</span><br><span class="line">        <span class="keyword">return</span> cls._instance</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">task</span>(<span class="params">name</span>):</span></span><br><span class="line">    obj = Singleton2(name)</span><br><span class="line">    <span class="built_in">print</span>(obj)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">20</span>):</span><br><span class="line">    t = threading.Thread(target=task, args=[i, ])</span><br><span class="line">    t.start()</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">Output</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x0000021B497307F0&gt;</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<p>优化：判断对象时都需要再次抢锁，这会大大降低执行效率，直接在抢锁前，判断下是否有单例对象，如果有就不再往下抢锁</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> time</span><br><span class="line"><span class="keyword">import</span> threading</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Singleton2</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line"></span><br><span class="line">    _instance_lock = threading.RLock()</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__init__</span>(<span class="params">self, name</span>):</span></span><br><span class="line">        self.name = name</span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">__new__</span>(<span class="params">cls, *args, **kwargs</span>):</span></span><br><span class="line">        <span class="keyword">if</span> <span class="keyword">not</span> <span class="built_in">hasattr</span>(cls, <span class="string">&quot;_instance&quot;</span>):</span><br><span class="line">            <span class="keyword">with</span> cls._instance_lock:</span><br><span class="line">                <span class="keyword">if</span> <span class="keyword">not</span> <span class="built_in">hasattr</span>(cls, <span class="string">&quot;_instance&quot;</span>):</span><br><span class="line">                    time.sleep(<span class="number">1</span>)   <span class="comment"># 耗时操作</span></span><br><span class="line">                    cls._instance = <span class="built_in">object</span>.__new__(cls)</span><br><span class="line">        <span class="keyword">return</span> cls._instance</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">def</span> <span class="title">task</span>(<span class="params">name</span>):</span></span><br><span class="line">    obj = Singleton2(name)</span><br><span class="line">    <span class="built_in">print</span>(obj)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">for</span> i <span class="keyword">in</span> <span class="built_in">range</span>(<span class="number">20</span>):</span><br><span class="line">    t = threading.Thread(target=task, args=[i, ])</span><br><span class="line">    t.start()</span><br><span class="line"></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br><span class="line"><span class="string">Output</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">    &lt;__main__.Singleton2 object at 0x000001ED48820828&gt;</span></span><br><span class="line"><span class="string">&quot;&quot;&quot;</span></span><br></pre></td></tr></table></figure>

<h1 id="二、工厂模式"><a href="#二、工厂模式" class="headerlink" title="二、工厂模式"></a>二、工厂模式</h1><h3 id="定义"><a href="#定义" class="headerlink" title="定义"></a>定义</h3><p>工厂模式（Factory Pattern）是最常用的设计模式之一。这种类型的设计模式属于创建型模式，它提供了一种创建对象的最佳方式。</p>
<p>工厂模式分为三种形式</p>
<ul>
<li>简单工厂模式（Simple Factory）</li>
<li>工厂方法模式（Factory Method）</li>
<li>抽象工厂模式（Abstract Factory）</li>
</ul>
<h5 id="简单工厂模式"><a href="#简单工厂模式" class="headerlink" title="简单工厂模式"></a>简单工厂模式</h5><p>结构：</p>
<ul>
<li>工厂角色（Creator）：这是简单工厂模式的核心，由它负责创建所有的类的内部逻辑。工厂类必须能够被外界调用，创建所需要的产品对象。</li>
<li>抽象（Product）产品角色：简单工厂模式所创建的所有对象的父类</li>
<li>具体产品（Concrete Product）角色：简单工厂所创建的具体实例对象，这些具体的产品往往都拥有共同的父类。</li>
</ul>
<p>优缺点：</p>
<p>工厂类中可以判断客户的的选择来动态实例化相关的类，对于客户端来说，去除了具体产品的依赖<br>但不符合OCP（开闭原则）：一个软件的实体应当对扩展开放，对修改关闭，如果要修改创建新的产品就需要修改工厂类</p>
<p>举例：通过简单工厂模式创建苹果和梨，一个工厂对象通过传入参数来创建不同对象</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment"># 产品</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AbstractConfig</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">show_name</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Apple</span>(<span class="params">AbstractConfig</span>):</span></span><br><span class="line">    name = <span class="string">&quot;苹果&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">show_name</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="built_in">print</span>(self.name)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Pear</span>(<span class="params">AbstractConfig</span>):</span></span><br><span class="line">    name = <span class="string">&quot;梨&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">show_name</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="built_in">print</span>(self.name)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">config_type = &#123;</span><br><span class="line">            <span class="string">&quot;apple&quot;</span>: <span class="string">&quot;Apple&quot;</span>,</span><br><span class="line">            <span class="string">&quot;pear&quot;</span>: <span class="string">&quot;Pear&quot;</span></span><br><span class="line">        &#125;</span><br><span class="line"><span class="comment"># 工厂</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">FruitsFactory</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @staticmethod</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">create_fruits</span>(<span class="params">app_name</span>):</span></span><br><span class="line">        <span class="comment"># flask</span></span><br><span class="line">        <span class="keyword">return</span> <span class="built_in">eval</span>(app_name)()  <span class="comment"># 调用不同的对象，实例化出想要的对象</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    factory = FruitsFactory()</span><br><span class="line">    apple = factory.create_fruits(config_type[<span class="string">&quot;apple&quot;</span>])</span><br><span class="line">    pear = factory.create_fruits(config_type[<span class="string">&quot;pear&quot;</span>])</span><br><span class="line"></span><br><span class="line">    apple.show_name()  <span class="comment"># 苹果</span></span><br><span class="line">    pear.show_name()  <span class="comment"># 梨</span></span><br></pre></td></tr></table></figure>

<h5 id="工厂方法模式"><a href="#工厂方法模式" class="headerlink" title="工厂方法模式"></a>工厂方法模式</h5><p>结构：</p>
<ul>
<li>抽象工厂类厂（AbstractFactory）：工厂方法模式的核心类，提供创建具体产品的接口，由具体工厂类实现。</li>
<li>具体工厂类（Producer）：继承于抽象工厂，实现创建对应具体产品对象的方式。</li>
<li>抽象产品类（Factory）：它是具体产品继承的父类（基类）。</li>
<li>具体产品类（Factory1）：具体工厂所创建的对象，就是此类</li>
</ul>
<p>优缺点：</p>
<ul>
<li>可以避免创建者和具体产品之间的紧密耦合。</li>
<li>单一职责原则。 你可以将产品创建代码放在程序的单一位置， 从而使得代码更容易维护。</li>
<li>开闭原则。 无需更改现有客户端代码， 你就可以在程序中引入新的产品类型。</li>
<li>应用工厂方法模式需要引入许多新的子类， 代码可能会因此变得更复杂。</li>
</ul>
<p>举例：通过工厂方法模式创建苹果和梨，单个具体工厂类创建单个具体产品对象</p>
<figure class="highlight python"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment"># 产品</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AbstractConfig</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">show_name</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Apple</span>(<span class="params">AbstractConfig</span>):</span></span><br><span class="line">    name = <span class="string">&quot;苹果&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">show_name</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="built_in">print</span>(self.name)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">Pear</span>(<span class="params">AbstractConfig</span>):</span></span><br><span class="line">    name = <span class="string">&quot;梨&quot;</span></span><br><span class="line"></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">show_name</span>(<span class="params">self</span>):</span></span><br><span class="line">        <span class="built_in">print</span>(self.name)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment"># 工厂</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">BaseFactory</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line"><span class="meta">    @staticmethod</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">create_fruits</span>():</span></span><br><span class="line">        <span class="keyword">pass</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">AppleFactory</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @staticmethod</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">create_fruits</span>():</span></span><br><span class="line">        <span class="keyword">return</span> Apple()  <span class="comment"># 调用具体产品对象</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="class"><span class="keyword">class</span> <span class="title">PearFactory</span>(<span class="params"><span class="built_in">object</span></span>):</span></span><br><span class="line"></span><br><span class="line"><span class="meta">    @staticmethod</span></span><br><span class="line">    <span class="function"><span class="keyword">def</span> <span class="title">create_fruits</span>():</span></span><br><span class="line">        <span class="keyword">return</span> Pear()  <span class="comment"># 调用具体产品对象</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="keyword">if</span> __name__ == <span class="string">&quot;__main__&quot;</span>:</span><br><span class="line">    apple_f = AppleFactory()</span><br><span class="line">    apple = apple_f.create_fruits()</span><br><span class="line">    apple.show_name()   <span class="comment"># 苹果</span></span><br><span class="line"></span><br><span class="line">    pear_f = PearFactory()</span><br><span class="line">    pear = PearFactory.create_fruits()</span><br><span class="line">    pear.show_name()    <span class="comment"># 梨</span></span><br></pre></td></tr></table></figure>

<p>#####抽象工厂模式</p>
<p>结构：</p>
<ul>
<li>抽象工厂类厂（AbstractFactory）：工厂方法模式的核心类，提供创建具体产品的接口，由具体工厂类实现。</li>
<li>具体工厂类（Producer）：继承于抽象工厂，实现创建对应具体产品对象的方式。</li>
<li>抽象产品类（Factory）：它是具体产品继承的父类（基类）。</li>
<li>具体产品类（Factory1）：具体工厂所创建的对象，就是此类。</li>
</ul>
<p>优缺点：</p>
<ul>
<li>可以确保同一工厂生成的产品相互匹配。可以避免客户端和具体产品代码的耦合。</li>
<li>单一职责原则。 你可以将产品生成代码抽取到同一位置， 使得代码易于维护。</li>
<li>开闭原则。 向应用程序中引入新产品变体时， 你无需修改客户端代码。</li>
<li>由于采用该模式需要向应用中引入众多接口和类， 代码可能会比之前更加复杂。</li>
</ul>
<p>举例：通过抽象工厂模式创建不同的午饭套餐</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br></pre></td><td class="code"><pre><span class="line"># 产品</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class StapleFoodBase(object):</span><br><span class="line">    &quot;&quot;&quot;主食&quot;&quot;&quot;</span><br><span class="line">    def show_name(self):</span><br><span class="line">        pass</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class Rice(StapleFoodBase):</span><br><span class="line">    def show_name(self):</span><br><span class="line">        return &quot;米饭&quot;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class Noodles(StapleFoodBase):</span><br><span class="line">    def show_name(self):</span><br><span class="line">        return &quot;面条&quot;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class DishBase(object):</span><br><span class="line">    &quot;&quot;&quot;菜名&quot;&quot;&quot;</span><br><span class="line">    def show_name(self):</span><br><span class="line">        pass</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class HongSaoRou(DishBase):</span><br><span class="line">    def show_name(self):</span><br><span class="line">        return &quot;红烧肉&quot;</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class HuiGuoRou(DishBase):</span><br><span class="line">    def show_name(self):</span><br><span class="line">        return &quot;回锅肉&quot;</span><br><span class="line"></span><br><span class="line"># 工厂</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class RiceBaseFactory(object):</span><br><span class="line">    pass</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class RiceHSRFactory(RiceBaseFactory):</span><br><span class="line">    &quot;&quot;&quot;红烧肉米饭&quot;&quot;&quot;</span><br><span class="line">    def __init__(self):</span><br><span class="line">        self.main_food = Rice()</span><br><span class="line">        self.dish = HongSaoRou()</span><br><span class="line"></span><br><span class="line">    def show(self):</span><br><span class="line">        return self.main_food.show_name() + self.dish.show_name()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class RiceHGRFactory(RiceBaseFactory):</span><br><span class="line">    &quot;&quot;&quot;回锅肉米饭&quot;&quot;&quot;</span><br><span class="line">    def __init__(self):</span><br><span class="line">        self.main_food = Rice()</span><br><span class="line">        self.dish = HongSaoRou()</span><br><span class="line"></span><br><span class="line">    def show(self):</span><br><span class="line">        return self.main_food.show_name() + self.dish.show_name()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class NoodlesBaseFactory(object):</span><br><span class="line">    pass</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class NoodlesHSRFactory(NoodlesBaseFactory):</span><br><span class="line">    &quot;&quot;&quot;红烧肉面条&quot;&quot;&quot;</span><br><span class="line">    def __init__(self):</span><br><span class="line">        self.main_food = Noodles()</span><br><span class="line">        self.dish = HongSaoRou()</span><br><span class="line"></span><br><span class="line">    def show(self):</span><br><span class="line">        return self.main_food.show_name() + self.dish.show_name()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">class NoodlesHGRFactory(NoodlesBaseFactory):</span><br><span class="line">    &quot;&quot;&quot;回锅肉面条&quot;&quot;&quot;</span><br><span class="line">    def __init__(self):</span><br><span class="line">        self.main_food = Noodles()</span><br><span class="line">        self.dish = HongSaoRou()</span><br><span class="line"></span><br><span class="line">    def show(self):</span><br><span class="line">        return self.main_food.show_name() + self.dish.show_name()</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">if __name__ == &quot;__main__&quot;:</span><br><span class="line">    f1 = RiceHSRFactory()</span><br><span class="line">    f2 = RiceHGRFactory()</span><br><span class="line">    f3 = NoodlesHSRFactory()</span><br><span class="line">    f4 = NoodlesHGRFactory()</span><br><span class="line"></span><br><span class="line">    print(</span><br><span class="line">        f1.show(),      # 米饭红烧肉</span><br><span class="line">        f2.show(),      # 米饭红烧肉</span><br><span class="line">        f3.show(),      # 面条红烧肉</span><br><span class="line">        f4.show(),      # 面条红烧肉</span><br><span class="line">    )</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<p>工厂方法模式和抽象工厂模式区别</p>
<table>
<thead>
<tr>
<th>工厂方法模式</th>
<th>抽象工厂模式</th>
</tr>
</thead>
<tbody><tr>
<td>针对的是一个产品等级结构</td>
<td>针对的是面向多个产品等级结构</td>
</tr>
<tr>
<td>一个抽象产品类</td>
<td>多个抽象产品类</td>
</tr>
<tr>
<td>可以派生出多个具体产品类</td>
<td>每个抽象产品类可以派生出多个具体产品类</td>
</tr>
<tr>
<td>一个抽象工厂类，可以派生出多个具体工厂类</td>
<td>一个抽象工厂类，可以派生出多个具体工厂类</td>
</tr>
<tr>
<td>每个具体工厂类只能创建一个具体产品类的实例</td>
<td>每个具体工厂类可以创建多个具体产品类的实例</td>
</tr>
</tbody></table>

    </div>

    
    
    
        

<div>
<ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者： </strong>二扬
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://eryangz.gitee.io/20190120/%E5%88%9D%E8%AF%86%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%E5%92%8C%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F/" title="初识单例模式和工厂模式">https://eryangz.gitee.io/20190120/初识单例模式和工厂模式/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" rel="noopener" target="_blank"><i class="fa fa-fw fa-creative-commons"></i>BY-NC-SA</a> 许可协议。转载请注明出处！
  </li>
</ul>
</div>


      <footer class="post-footer">
          
          <div class="post-tags">
              <a href="/tags/python/" rel="tag"><i class="fa fa-tag"></i> python</a>
              <a href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="tag"><i class="fa fa-tag"></i> 设计模式</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item"></div>
      <div class="post-nav-item">
    <a href="/20190621/git%E9%85%8D%E7%BD%AE%E4%BB%93%E5%BA%93/" rel="next" title="git配置仓库">
      git配置仓库 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F"><span class="nav-text">一、单例模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%9A%E4%B9%89%E5%8F%8A%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86"><span class="nav-text">定义及实现原理</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#%E9%80%9A%E8%BF%87%E6%A8%A1%E5%9D%97%E5%AE%9E%E7%8E%B0"><span class="nav-text">通过模块实现</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E9%80%9A%E8%BF%87%E8%A3%85%E9%A5%B0%E5%99%A8%E5%AE%9E%E7%8E%B0"><span class="nav-text">通过装饰器实现</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E7%B1%BB%E6%96%B9%E6%B3%95%E3%80%81%E9%AD%94%E6%B3%95%E6%96%B9%E6%B3%95"><span class="nav-text">使用类方法、魔法方法</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E5%85%83%E7%B1%BB%E5%AE%9E%E7%8E%B0"><span class="nav-text">元类实现</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%B9%B6%E5%8F%91%E6%83%85%E5%86%B5%E4%B8%8B%E5%8D%95%E4%BE%8B%E6%A8%A1%E5%BC%8F%E7%9A%84%E4%BC%98%E5%8C%96"><span class="nav-text">多线程并发情况下单例模式的优化</span></a></li></ol></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F"><span class="nav-text">二、工厂模式</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%9A%E4%B9%89"><span class="nav-text">定义</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#%E7%AE%80%E5%8D%95%E5%B7%A5%E5%8E%82%E6%A8%A1%E5%BC%8F"><span class="nav-text">简单工厂模式</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E5%B7%A5%E5%8E%82%E6%96%B9%E6%B3%95%E6%A8%A1%E5%BC%8F"><span class="nav-text">工厂方法模式</span></a></li></ol></li></ol></li></ol></li></ol></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="二扬"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">二扬</p>
  <div class="site-description" itemprop="description">念念不忘, 必有回响</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">26</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">27</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author motion-element">
      <span class="links-of-author-item">
        <a href="https://github.com/EryangZzz" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;EryangZzz" rel="noopener" target="_blank"><i class="fa fa-fw fa-github"></i>GitHub</a>
      </span>
      <span class="links-of-author-item">
        <a href="https://gitee.com/" title="Gitee → https:&#x2F;&#x2F;gitee.com&#x2F;" rel="noopener" target="_blank"><i class="fa fa-fw fa-github-alt"></i>Gitee</a>
      </span>
      <span class="links-of-author-item">
        <a href="/1289256052" title="QQ → 1289256052"><i class="fa fa-fw fa-qq"></i>QQ</a>
      </span>
      <span class="links-of-author-item">
        <a href="/1289256052@qq.com" title="E-Mail → 1289256052@qq.com"><i class="fa fa-fw fa-envelope"></i>E-Mail</a>
      </span>
  </div>



<script type="text/javascript" charset="utf-8" src="/js/tagcloud.js"></script>
<script type="text/javascript" charset="utf-8" src="/js/tagcanvas.js"></script>
<div class="widget-wrap">
    <iframe frameborder="no" border="0" marginwidth="0" marginheight="0" width=330 height=110 src="//music.163.com/outchain/player?type=0&id=8435349308&auto=1&height=66"></iframe>
    <h3 class="widget-title">标签云</h3>
    <div id="myCanvasContainer" class="widget tagcloud">
        <canvas width="250" height="250" id="resCanvas" style="width=100%">
            <ul class="tag-list" itemprop="keywords"><li class="tag-list-item"><a class="tag-list-link" href="/tags/emqx/" rel="tag">emqx</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/flask/" rel="tag">flask</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/git/" rel="tag">git</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/js/" rel="tag">js</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/metaclass/" rel="tag">metaclass</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/mqtt/" rel="tag">mqtt</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/nginx/" rel="tag">nginx</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/odoo/" rel="tag">odoo</a><span class="tag-list-count">10</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/odoo%E5%89%8D%E7%AB%AF/" rel="tag">odoo前端</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/odoo%E9%83%A8%E7%BD%B2/" rel="tag">odoo部署</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/office%E9%A2%84%E8%A7%88/" rel="tag">office预览</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/pgsql/" rel="tag">pgsql</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/pip%E6%BA%90/" rel="tag">pip源</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/pyinstaller/" rel="tag">pyinstaller</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/python/" rel="tag">python</a><span class="tag-list-count">9</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/re/" rel="tag">re</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/rtsp/" rel="tag">rtsp</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/time%E6%A8%A1%E5%9D%97/" rel="tag">time模块</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/ubuntu/" rel="tag">ubuntu</a><span class="tag-list-count">4</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/ubuntu%E6%BA%90/" rel="tag">ubuntu源</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E5%85%83%E7%B1%BB/" rel="tag">元类</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E5%A4%9A%E7%BA%BF%E7%A8%8B/" rel="tag">多线程</a><span class="tag-list-count">2</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E6%9C%8D%E5%8A%A1%E9%85%8D%E7%BD%AE/" rel="tag">服务配置</a><span class="tag-list-count">6</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E6%AD%A3%E5%88%99%E8%A1%A8%E8%BE%BE%E5%BC%8F/" rel="tag">正则表达式</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E7%AC%91%E8%84%B8%E4%BA%A4%E4%BA%92/" rel="tag">笑脸交互</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E8%A7%86%E9%A2%91%E6%B5%81/" rel="tag">视频流</a><span class="tag-list-count">1</span></li><li class="tag-list-item"><a class="tag-list-link" href="/tags/%E8%AE%BE%E8%AE%A1%E6%A8%A1%E5%BC%8F/" rel="tag">设计模式</a><span class="tag-list-count">1</span></li></ul>
        </canvas>
    </div>
</div>




      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">二扬</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
      <span class="post-meta-item-text">站点总字数：</span>
    <span title="站点总字数">105k</span>
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span class="post-meta-item-text">站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">1:35</span>
</div>



        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  
  <script>
    (function(){
      var bp = document.createElement('script');
      var curProtocol = window.location.protocol.split(':')[0];
      bp.src = (curProtocol === 'https') ? 'https://zz.bdstatic.com/linksubmit/push.js' : 'http://push.zhanzhang.baidu.com/push.js';
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(bp, s);
    })();
  </script>
<script>
(function(){
var bp = document.createElement('script');
var curProtocol = window.location.protocol.split(':')[0];
if (curProtocol === 'https') {
bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
}
else {
bp.src = 'http://push.zhanzhang.baidu.com/push.js';
}
 var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(bp, s);
})();
</script>





  
<script src="/js/local-search.js"></script>













  

  

</body>
</html>
